<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>LineStyle</title>
  <style>
    canvas{
      border: 1px solid gray;
    }
  </style>
</head>
<body>
  <canvas id="canvas" width="500" height="800">您的浏览器不支持Canvas！</canvas>
</body>
<script>
  const canvas = document.getElementById("canvas");
  // 获取上下文以及绘画功能
  const ctx = canvas.getContext("2d");

  // 不同宽度线条
  for(let i = 0; i < 10 ; i++){
    ctx.lineWidth = i + 1;
    ctx.beginPath();
    ctx.moveTo(5 + i * 10, 5);
    ctx.lineTo(5 + i * 10, 150);
    ctx.stroke();
  }

  // 设置末端样式
  const lineCap = ['butt','round','square'];
  ctx.lineWidth = 1;
  // 创建路径
  ctx.strokeStyle = '#09f';
  ctx.beginPath();
  ctx.moveTo(10,210);
  ctx.lineTo(140,210);
  ctx.moveTo(10,340);
  ctx.lineTo(140,340);
  ctx.stroke();

  // 画线条
  ctx.strokeStyle = 'black';
  for (var i=0;i<lineCap.length;i++){
    ctx.lineWidth = 15;
    ctx.lineCap = lineCap[i];
    ctx.beginPath();
    ctx.moveTo(25+i*50,210);
    ctx.lineTo(25+i*50,340);
    ctx.stroke();
  }

  // lineJoin交叉处理
  var lineJoin = ['round', 'bevel', 'miter'];
  ctx.lineWidth = 10;
  for (var i = 0; i < lineJoin.length; i++) {
    ctx.lineJoin = lineJoin[i];
    ctx.beginPath();
    ctx.moveTo(15, 505 + i * 40);
    ctx.lineTo(55, 545 + i * 40);
    ctx.lineTo(95, 505 + i * 40);
    ctx.lineTo(135, 545 + i * 40);
    ctx.lineTo(175, 505 + i * 40);
    ctx.stroke();
  }

  // 虚线样式
  let offset1 = 0;
  ctx.lineWidth = 1;

  draw = () => {
    ctx.beginPath();
    ctx.setLineDash([4, 2]);
    ctx.lineDashOffset = -offset1;
    ctx.strokeRect(300, 10, 100, 100);
  }
  march = () => {
    offset1 ++;
    if(offset1 > 16){
      offset1 = 0;
    }
    draw();
    setTimeout(march, 20);
  }
  march();

  var offset = 0;
  ctx.lineWidth = 1;
  function draw() {
  ctx.clearRect(0,0, canvas.width, canvas.height);
  ctx.setLineDash([4, 2]);
  ctx.lineDashOffset = -offset;
  ctx.strokeRect(10,10, 100, 100);
}

function march() {
  offset++;
  if (offset > 16) {
    offset = 0;
  }
  draw();
  setTimeout(march, 20);
}

march();


</script>
</html>